package com.bestcem.xm.award.config;

import com.bestcem.xm.common.core.domain.web.ServiceResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

/**
 * @author xa.zhang <xa.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021/7/6 15:26
 * @desc 用来处理奖励未知的通用异常
 */
@Slf4j
@Component
@Aspect
public class AwardExceptionAspect {

    /**
     * 奖励的service公共方法拦截
     */
    @Pointcut("execution(public com.bestcem.xm.common.core.domain.web.ServiceResult com.bestcem.xm.award.service.*.*(..))")
    public void exceptionPointCut() {
    }


    /**
     * 只对奖励的service返回值类型为 ServiceResult的异常进行转换为ServiceResult.fail("系统异常")
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("exceptionPointCut()")
    public Object exceptionCheck(ProceedingJoinPoint joinPoint)  {

        long beginTime = System.currentTimeMillis();

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Type type = method.getGenericReturnType();

        log.info("start execute:{}", method.toString());

        Object result = null;
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            log.error("around", e);
            if (type.getTypeName().startsWith(ServiceResult.class.getTypeName())) {
                log.error("around", e);
                result = ServiceResult.fail("系统异常");
            }
        }
        long end = System.currentTimeMillis() - beginTime;
        log.info("cost:{},end execute:{}", end, method.toString());
        return result;
    }


}
